<template>
  <div class="compare-container">
    <el-skeleton :loading="loading" animated :rows="6"/>

    <div v-if="!loading && compareData" class="content-wrapper">
      <!-- 总览对比 -->
      <el-card class="info-card" :body-style="{ padding: '20px 15px' }">
        <template #header>
          <div class="card-header">
            <div class="header-wrapper">
              <span class="title">测评总览对比</span>
              <el-button class="back-btn" type="info" circle :icon="ArrowLeft" @click="handleBack" />
            </div>
          </div>
        </template>
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="chart-card">
              <h4 class="chart-title">总分对比</h4>
              <div class="chart-container">
                <v-chart :option="scoreOption" autoresize/>
              </div>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="chart-card">
              <h4 class="chart-title">耗时对比（分钟）</h4>
              <div class="chart-container">
                <v-chart :option="timeOption" autoresize/>
              </div>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <!-- 维度对比 -->
      <el-card class="dimension-card" :body-style="{ padding: '20px 15px' }">
        <template #header>
          <div class="card-header">
            <span class="title">维度得分对比</span>
          </div>
        </template>
        <div class="chart-container">
          <v-chart :option="dimensionOption" autoresize/>
        </div>
      </el-card>

      <!-- 专业分析 -->
      <!--<el-card class="radar-card">
        <template #header>
          <div class="card-header">
            <span class="title">专业维度分析</span>
          </div>
        </template>
        <div class="chart-container">
          <v-chart :option="radarOption" autoresize/>
        </div>
      </el-card>-->
    </div>

    <el-empty v-if="!loading && !compareData" description="未找到对比数据"/>
  </div>
</template>

<script setup>
import {ref, computed, onMounted, getCurrentInstance} from 'vue'
import {use} from 'echarts/core'
import {CanvasRenderer} from 'echarts/renderers'
import {BarChart, LineChart, RadarChart} from 'echarts/charts'
import {GridComponent, LegendComponent, TitleComponent, TooltipComponent} from 'echarts/components'
import VChart from 'vue-echarts'
import * as echarts from 'echarts'
import {compareHistoryRecord} from "@/api/record/record.js"
import { ArrowLeft } from '@element-plus/icons-vue'

// ECharts 初始化
use([
  CanvasRenderer,
  BarChart,
  LineChart,
  RadarChart,
  GridComponent,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
])

const {proxy} = getCurrentInstance();
const loading = ref(true)
const compareData = ref(null)
const currentId = ref(proxy.$route.query.currentId)
const compareId = ref(proxy.$route.query.compareId)

const handleBack = () => {
  proxy.$router.push('/history') // 根据实际路由调整
  // 或者返回上一页：proxy.$router.go(-1)
}

const formatTime = (milliseconds) => {
  // 将毫秒转换为分钟：1分钟 = 60,000毫秒
  // 使用toFixed(1)保留1位小数
  return (milliseconds / 60000).toFixed(1)
}

// 通用数据获取方法
const getChartData = (key) => ({
  current: key === 'totalTime'
      ? formatTime(compareData.value?.current?.[key] || 0)  // 特殊处理耗时字段
      : compareData.value?.current?.[key] || 0,
  history: key === 'totalTime'
      ? formatTime(compareData.value?.history?.[key] || 0)
      : compareData.value?.history?.[key] || 0
})

const baseChartOptions = {
  animation: true,
  animationDuration: 1200,  // 延长动画时间
  animationEasing: 'elasticOut',  // 使用更有弹性的缓动函数
  animationDelay: 200  // 添加初始延迟
}

// 总分对比配置
const scoreOption = computed(() => {
  const data = getChartData('totalScore')
  return {
    ...baseChartOptions,
    title: {text: '总分对比', left: 'center'},
    tooltip: {trigger: 'axis', formatter: '{b}: {c} 分'},
    xAxis: {
      type: 'category',
      data: ['当前记录', '历史记录'],
      axisLabel: {color: '#606266'}
    },
    yAxis: {type: 'value', min: 0},
    series: [{
      data: [data.current, data.history],
      type: 'bar',
      itemStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          {offset: 0, color: '#36a2eb'},
          {offset: 1, color: '#4ecb73'}
        ]),
        borderRadius: [4, 4, 0, 0]
      },
      label: {
        show: true,
        position: 'top',
        formatter: '{c}分'
      }
    }]
  }
})

// 耗时对比配置
const timeOption = computed(() => {
  const data = getChartData('totalTime')
  return {
    ...baseChartOptions,
    title: {text: '耗时对比', left: 'center'},
    tooltip: {
      trigger: 'axis',
      formatter: params => {
        return `${params[0].name}<br/>${params[0].marker} ${params[0].value} 分钟`
      }
    },
    xAxis: {
      type: 'category',
      data: ['当前记录', '历史记录'],
      axisLabel: {color: '#606266'}
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: value => value + ' 分钟' // Y轴显示单位
      }
    },
    series: [{
      data: [data.current, data.history],
      type: 'line',
      smooth: true,
      lineStyle: {width: 3, color: '#ff9f43'},
      symbolSize: 8,
      itemStyle: {color: '#ff9f43'},
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          {offset: 0, color: 'rgba(255,159,67,0.3)'},
          {offset: 1, color: 'rgba(255,159,67,0.05)'}
        ])
      }
    }]
  }
})

// 维度对比配置
const dimensionOption = computed(() => {
  const currentData = compareData.value?.current?.symptomClusterDTOList || []
  const historyData = compareData.value?.history?.symptomClusterDTOList || []

  return {
    ...baseChartOptions,
    title: {text: '维度得分对比', left: 'center'},
    tooltip: {trigger: 'axis'},
    legend: {top: 30},
    xAxis: {
      type: 'category',
      data: currentData.map(d => d.name),
      axisLabel: {rotate: 45}
    },
    yAxis: {type: 'value', min: 0},
    grid: {top: 80},
    series: [
      {
        name: '当前记录',
        type: 'bar',
        data: currentData.map(d => d.score),
        itemStyle: {color: '#4ecb73'}
      },
      {
        name: '历史记录',
        type: 'bar',
        data: historyData.map(d => d.score),
        itemStyle: {color: '#36a2eb'}
      }
    ]
  }
})

// 雷达图配置
const radarOption = computed(() => {
  const currentData = compareData.value?.current?.symptomClusterDTOList || []
  const historyData = compareData.value?.history?.symptomClusterDTOList || []

  return {
    title: {text: '专业维度分析', left: 'center'},
    tooltip: {trigger: 'item'},
    legend: {top: 30},
    radar: {
      indicator: currentData.map(d => ({
        name: d.name,
        max: Math.max(...currentData.map(d => d.score), ...historyData.map(d => d.score)) * 1.2
      })),
      shape: 'polygon'
    },
    series: [{
      type: 'radar',
      data: [
        {
          name: '当前记录',
          value: currentData.map(d => d.score),
          areaStyle: {color: 'rgba(78, 203, 115, 0.4)'}
        },
        {
          name: '历史记录',
          value: historyData.map(d => d.score),
          areaStyle: {color: 'rgba(54, 162, 235, 0.4)'}
        }
      ]
    }]
  }
})

// 获取数据
const fetchCompareData = async () => {
  loading.value = true
  try {
    const res = await compareHistoryRecord(currentId.value, compareId.value)
    // 先重置数据确保动画触发
    compareData.value = null
    // 使用nextTick确保DOM更新
    await nextTick()
    compareData.value = res.data
  } catch (error) {
    console.error('获取对比数据失败:', error)
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchCompareData();
})
</script>

<style scoped>
.title {
  font-size: 18px;
  color: #303133;
  font-weight: 600;
  flex-grow: 1;
}
.card-header {
  width: 100%;
}

.header-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}
.back-btn {
  padding: 7px 15px;
  border-radius: 18px;
  transition: all 0.3s ease;
  margin-left: auto;

  &:hover {
    transform: translateX(-3px);
    background: #909399;
  }

  .el-icon {
    margin-right: 5px;
    font-size: 14px;
  }
}
.compare-container {
  background: linear-gradient(135deg, #f0f9ff 0%, #ffffff 100%);
  min-height: auto;
  padding: 15px;
  box-sizing: border-box;
}

.info-card, .dimension-card, .radar-card {
  margin-bottom: 12px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.chart-card {
  background: #fff;
  border-radius: 8px;
  padding: 15px;
  height: 490px;
}

.chart-title {
  margin: 0 0 8px;
  color: #2c3e50;
  font-size: 14px;
  font-weight: 600;
}

.chart-container {
  height: 480px;
  position: relative;

  .echarts {
    width: 100%;
    height: 100%;
  }
}

.dimension-card .chart-container {
  height: 400px;
}

.radar-card .chart-container {
  height: 700px;
}
</style>
